# 各种统计信息
Q = require("q")

config = require('../config')
Schema = config.Schema
mongoose = config.mongoose

DictSchema = new Schema({
  id:
    type: String
    default: "basic"
  dict:
    type: Schema.Types.Mixed
    default: {}
})

DictSchema.set('autoIndex',false)
DictSchema.index {id:1}


DictSchema.statics.get = (attr, id="basic") ->
  
  if typeof(attr) == "string"
    tmp = {}
    tmp[attr] = 1
    attr = tmp

  params = {}
  for k,v of attr
    params["dict." + k] = v
    
  Q.ninvoke(Dict,"findOne", {id}, params)
    .then (result) ->
      return result?.dict


DictSchema.statics.set = (attr, value, id="basic") ->
  
  if typeof(attr) == "string"
    tmp = {}
    tmp[attr] = value
    attr = tmp
  else # attr is object
    id = value or id

  Q.ninvoke(Dict,"findOne",{id})
    .then (result) ->
      if result
        params = {}
        for k,v of attr
          params["dict." + k] = v
        console.debug JSON.stringify params          
        Q.ninvoke(Dict, "update", {id}, {$set: params})
      else
        obj = new Dict {id, dict: attr}
        Q.ninvoke(obj,"save")

exports.Dict = Dict = mongoose.model "hsdict", DictSchema        


 
